<template>
  <div class="edit">
    <van-nav-bar :title="title" class="head">
      <template #left>
        <i @click="$router.go(-1)" class="iconfont iconbtn_nav_back myicon"></i>
      </template>
      <template #right>
        <span v-if="isShow" @click="submit">保存</span>
      </template>
    </van-nav-bar>
    <div class="main">
      <van-uploader
        max-count="1"
        preview-size="200px"
        class="userIcon"
        v-model="firstList"
        :after-read="afterRead"
        v-if="$route.query.property === 'avatar'"
      />
      <van-field
        class="myField"
        v-model="value"
        @input="isShow = true"
        v-else
      />
    </div>
  </div>
</template>
<script>
import { editUser, getImg } from '@/api/user'
import { mapState } from 'vuex'
export default {
  data () {
    return {
      isShow: false,
      title: '',
      value: '',
      avatar: 0,
      firstList: [
        {
          url:
            'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1208777900,2205110458&fm=26&gp=0.jpg'
        }
      ]
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.userInfo
    })
  },
  created () {
    const property = this.$route.query.property
    if (property === 'nickname') {
      this.title = '修改昵称'
    } else if (property === 'intro') {
      this.title = '修改个性签名'
    } else if (property === 'avatar') {
      this.title = '修改头像'
    } else if (property === 'position') {
      this.title = '修改我的岗位'
    }
    this.value = this.userInfo.property
    this.firstList[0].url = this.userInfo.avatar
  },
  methods: {
    async afterRead (file) {
      this.isShow = true
      // console.log('file', file)
      file.status = 'uploading'
      file.message = '上传中...'
      const res = await getImg(file.file)
      this.avatar = res.data[0].id
      file.status = 'done'
    },
    async submit () {
      this.$toast.loading({
        duration: 0
      })
      const property = this.$route.query.property
      await editUser({ [property]: this[property] })
      this.$toast.success('修改成功')
      this.$store.dispatch('setUserInfo')
      this.$router.push('/info')
    }
  }
}
</script>
<style lang="less">
.edit {
  font-size: 12px;
  .head {
    .myicon {
      font-size: 30px;
    }
  }
  .main {
    margin: 15px;
    border-radius: 10px;
    text-align: center;
    .userIcon {
      text-align: center;
    }
    .myField {
      background-color: #eee;
    }
    // background-color: red;
  }
}
</style>
